package com.lzy.wzy.handle;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzy.wzy.exception.DepartmentSelectionException;
import com.lzy.wzy.result.Response;
import com.lzy.wzy.result.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登陆失败");
        Response<T> rep=new Response<>();
        if (exception instanceof BadCredentialsException){
            rep.setStatus(ResponseCode.WRONG_PASSWORD.getCode());
            rep.setMsg(ResponseCode.WRONG_PASSWORD.getMsg());
            log.info("密码错误");
        }else if (exception instanceof DepartmentSelectionException){
            rep.setStatus(ResponseCode.DEPARTMENT_ERROR.getCode());
            rep.setMsg(exception.getMessage());
            log.info("DepartmentSelectionException");
        }else if (exception instanceof UsernameNotFoundException) {
            rep.setStatus(ResponseCode.USER_NOT_EXITS.getCode());
            rep.setMsg(ResponseCode.USER_NOT_EXITS.getMsg());
        }else if (exception instanceof DisabledException){
            rep.setStatus(ResponseCode.FAILURE.getCode());
            rep.setMsg("该账户已被禁用，请联系管理员");
        }else {
            rep.setStatus(ResponseCode.FAILURE.getCode());
            rep.setMsg(ResponseCode.FAILURE.getMsg());
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(rep));
        writer.flush();
}
}